<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo24-状态管理01</title>
</head>
<script src="../libs/vue.js"></script>
<style>
    .container{
        width: 100%;
        min-width: 320px;
        max-width: 640px;

        margin:0 auto;
    }
</style>
<body> 
  <div id="vma"> 
    <shcomponent></shcomponent>
  </div>
  <div id="vmb"> 
    <shcomponent></shcomponent>
  </div>
</body>

<script>

/**
 * 用这个例子，加深理解了 store的角色。
 * 
 * 使用ts的关键也是避免了this的指向问题。
 */  
var store = {
  debug: true,
  state: {
    message: 'Hello!'
  },
  setMessageAction (newValue) {
    if (this.debug) console.log('setMessageAction triggered with', newValue)
    this.state.message = newValue
  },
  clearMessageAction () {
    if (this.debug) console.log('clearMessageAction triggered')
    this.state.message = ''
  }
}


Vue.component('shcomponent',{
  data: function(){
    return {
      privateState: {
        title:'这是vm实例title'
      },
      sharedState: store.state
    }
  },
  template:`<div>
    <div><h1>{{privateState.title}}</h1></div>
    <div>
      <div>
        <span>{{sharedState.message}}</span>
      </div>
      <div>
        <button v-on:click="updateSharedState">点击更新sharedState.message</button>
      </div>
    </div>
  </div>`,
  methods:{
    updateSharedState: function(){
      var ran = Math.random();
      store.setMessageAction('更新随机值：'+ran);
    }
  }
});

var vma = new Vue({
  el:'#vma',
})

var vmb = new Vue({
  el:'#vmb',
})


</script>
</html>